package com.zx.framework.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * httpclient util
 * 
 * @author stylewolf
 * 
 */
public class HttpUtil {

	private static HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());

	private static final Logger LOGGER = Logger.getLogger(HttpUtil.class);
	/**
	 * post请求
	 * @param url
	 * @param reqEncoding
	 * @param respEncoding
	 * @param param
	 * @return
	 */
	public static String post(String url, String reqEncoding, String respEncoding,
			List<NameValuePair> param) {
		String rs = "";
		// 创建httpPost
		HttpPost httpPost = new HttpPost(url);
		// 创建参数队列
		List<NameValuePair> formparams = param;
		try {
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(
					formparams, reqEncoding);
			httpPost.setHeader("Accept", "application/json");
			httpPost.setEntity(uefEntity);
			
			HttpResponse response;
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				rs = EntityUtils.toString(entity, respEncoding);
			}
		} catch (Exception e) {
			LOGGER.error("",e);
			throw new RuntimeException ("post请求失败！");
		}finally{
			httpPost.releaseConnection();
		}
		return rs;
	}
	/**
	 * 默认使用utf-8请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static String post(String url, List<NameValuePair> param){
		return post(url, "UTF-8", "UTF-8", param);
	}
	
	/**
	 * 默认使用utf-8请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static String post(String url){
		return post(url, "UTF-8", "UTF-8", new ArrayList<NameValuePair>());
	}
	/**
	 * get请求
	 * @param url
	 * @param reqEncoding
	 * @param respEncoding
	 * @param params
	 * @return
	 */
	public static String get(String url, String reqEncoding, String respEncoding,List<NameValuePair> params) {
		String rs = "";
		// 创建httpPost
		HttpGet httpGet = new HttpGet(url);
		try {
			String query = EntityUtils.toString(new UrlEncodedFormEntity(params,reqEncoding));  
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + query)); 
			httpGet.setHeader("Accept", "application/json");
			HttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			rs = EntityUtils.toString(entity, respEncoding);
		} catch (Exception e) {
			LOGGER.error("",e);
			e.printStackTrace();
			throw new RuntimeException ("get请求失败！");
		}
		return rs;
	}
	
	/**
	 * 默认使用utf-8请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static String get(String url, List<NameValuePair> param){
		return get(url, "UTF-8", "UTF-8", param);
	}
	
	/**
	 * 默认使用utf-8请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static String get(String url){
		return get(url, "UTF-8", "UTF-8", new ArrayList<NameValuePair>());
	}
	
	public static String toString(final HttpEntity entity,
			final String defaultCharset) throws IOException,
			ParseException {
		if (entity == null) {
			throw new IllegalArgumentException(
					"HTTP entity may not be null");
		}
		InputStream instream = entity.getContent();
		if (instream == null) {
			return null;
		}
		try {
			if (entity.getContentLength() > Integer.MAX_VALUE) {
				throw new IllegalArgumentException(
						"HTTP entity too large to be buffered in memory");
			}
			int i = (int) entity.getContentLength();
			if (i < 0) {
				i = 4096;
			}
			Reader reader = new InputStreamReader(instream,
					defaultCharset);
			CharArrayBuffer buffer = new CharArrayBuffer(i);
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
			return buffer.toString();
		} finally {
			instream.close();
		}
	}
}
